package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author ：xu
 * @date ：Created in 2019/7/1
 * @description ：
 * @version: 1.0
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @RequestMapping("/loginOk")
    public Result loginOk(){
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }
    @RequestMapping("/loginError")
    public Result loginError(){
        return new Result(false, MessageConst.ACTION_FAIL);
    }

    @RequestMapping("/getUserName")
    public Result getUserName(HttpServletRequest request){
        //getSession(false)表示为如果没有session也不去创建session对象
        System.out.println("sessionID:"+request.getSession(false).getId());
        try {
            //从授权框架上下文获取授权对象,再从授权对象获取授权框架用户对象User 最后获取用户名
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = (User) authentication.getPrincipal();
            if (user != null){
                log.debug("user :{}",user);
                return new Result(true, MessageConst.ACTION_SUCCESS,user.getUsername());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, MessageConst.ACTION_FAIL);
    }

    /**
     * 添加用户
     * @param user
     * @param roleIds
     * @return
     */
    @RequestMapping("/add")
    public Result add(@RequestBody com.itheima.health.pojo.User user, Integer[] roleIds){
        try {
            log.debug("User: {},RoleIds: {}",user,roleIds);
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            System.out.println(user.getPassword());
            //调用userService 保存用户
            userService.add(user,roleIds);
            //成功返回成功信息
            return new Result(true, MessageConst.ACTION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            //失败返回错误信息
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        log.debug("queryPageBean :{}",queryPageBean);
        PageResult pageResult = null;
        try {
            //调用userService获取分页结果
             pageResult = userService.pageQuery
                    (queryPageBean.getCurrentPage(), queryPageBean.getPageSize(), queryPageBean.getQueryString());
        } catch (Exception e) {
            e.printStackTrace();
            //查询失败返回空
            pageResult = new PageResult(0L,null);
        }
        return pageResult;
    }

    /**
     * 通过id查询用户信息
     * @param id
     * @return
     */
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            //调用userService通过id查询用户信息
            com.itheima.health.pojo.User user = userService.findById(id);
            user.setPassword("1234");
            //返回成功信息
            return new Result(true,MessageConst.ACTION_SUCCESS,user);
        } catch (Exception e) {
            e.printStackTrace();
            //返回失败信息
            return new Result(false,MessageConst.ACTION_FAIL);
        }
    }

    /**
     * 通过用户id查询中间表获取用户的角色信息
     * @param id
     * @return
     */
    @RequestMapping("/findRoleIdsByUserId")
    public Result findRoleIdsByUserId(Integer id){
        try {
            //调用userService通过用户id查询中间表获取用户的角色信息
            List<Integer> roleIdList = userService.findRoleIdsByUserId(id);
            //返回成功信息
            return new Result(true,MessageConst.ACTION_SUCCESS,roleIdList);
        } catch (Exception e) {
            e.printStackTrace();
            //返回失败信息
            return new Result(false,MessageConst.ACTION_FAIL);
        }
    }

    @RequestMapping("/edit")
    public Result edit(@RequestBody com.itheima.health.pojo.User user,Integer [] roleIds){
        try {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            //调用userService编辑用户
            userService.editByUserId(user,roleIds);
            //返回成功信息
            return new Result(true,MessageConst.ACTION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            //返回失败信息
            return new Result(false,MessageConst.ACTION_FAIL);
        }
    }

    @RequestMapping("/delete")
    public Result delete(Integer id){
        try {
            //调用userService删除用户
            userService.deleteUserById(id);
            //返回成功信息
            return new Result(true,MessageConst.ACTION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            //返回失败信息
            return new Result(false,MessageConst.ACTION_FAIL);
        }
    }
}
